package lib.modules;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import flexjson.JSONSerializer;

import lib.base.EgoHoliday;
import lib.base.EgoModule;
import lib.data.Employee;

public class ModLeaveAccount extends EgoModule
{

	public ModLeaveAccount(HttpServletRequest req)
	{
		super(req);
		req.getSession().setAttribute("template", "modules/leave_account/index.jsp");
	}

	@Override
	public void work() throws Exception
	{
		String action = _request.getParameter("action");
		if (action != null)
		{
			if (action.equals("read"))
			{
				_read();
			} else if (action.equals("remaining"))
			{
				float r = _curCust.holidayManager.getRemainingLeaves(
						_curEmp,
						_curCust.holidayManager.getHolidays(_curEmp, _request.getParameter("year"))
				);
				// without remaining leaves from prev year
				r -= Float.parseFloat(_curEmp.getField("remainingLeavePrevYear").toString());
				_request.setAttribute("ajax_return", r);
			} else if (action.equals("del"))
			{
				_deleteEntry();
			}
			_request.getSession().setAttribute("template", "ajax_return.jsp");
		} else
		{
			_setParams();
		}
	}
	
	private void _read() throws Exception
	{
		ArrayList<EgoHoliday> x = _curCust.holidayManager.getHolidays(
			_curEmp
			, _request.getParameter("year")
		);

		Map<String,Object> data = new HashMap<String,Object>();
		
		data.put("identifier", "id");
		data.put("label", "start");
		
		ArrayList<Map<String,Object>> items = new ArrayList<Map<String,Object>>();
		for (int i=0; i<x.size(); i++)
		{
			Map<String, Object> attr = new HashMap<String, Object>();
			attr.put("id", String.valueOf(i));
			attr.put("start", x.get(i).getStartStamp());
			attr.put("end", x.get(i).getEndStamp());
			attr.put("type", x.get(i).getType());
			attr.put("length", x.get(i).getLength());
			attr.put("status", x.get(i).getStatus());
			items.add(attr);
		}
		
		data.put("items", items);

		_request.setAttribute("ajax_return", new JSONSerializer().serialize(data));
	}
	
	private void _setParams() throws Exception
	{
		Employee emp = _curEmp;
		_request.setAttribute("entitlementLeave",
			emp.getField("entitlementLeave").toString()
		);
		_request.setAttribute("remainingLeave",
			_curCust.holidayManager.getRemainingLeaves(emp, null)
		);
		_request.setAttribute("year",
			Calendar.getInstance().get(Calendar.YEAR)
		);
		_request.setAttribute("remainingLeavePrevYear",
				emp.getField("remainingLeavePrevYear").toString()
		);
	}
	
	private void _deleteEntry() throws Exception
	{
		EgoHoliday h = _curCust.holidayManager.getHoliday(
			_curEmp
			, _request.getParameter("start")
			, _request.getParameter("end")
		);
		_curCust.holidayManager.deleteHoliday(
			_curEmp
			, h
		);
	}
}
